
package com.zcp.pcsuitall.business;

import com.zcp.pcsuitall.Action;
import com.zcp.pcsuitall.BusinessControl;
import com.zcp.pcsuitall.IDealWithMessage;
import com.zcp.pcsuitall.R;
import com.zcp.pcsuitall.XmlDataDealWith;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;

import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Xml;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.channels.SocketChannel;

public class VideoManager implements IDealWithMessage {

    private static final String[] VIDEO_PROJECTION = new String[] {
            MediaStore.Video.VideoColumns._ID, // id index 0
            MediaStore.Video.VideoColumns.DISPLAY_NAME,// name index 1
            MediaStore.Video.VideoColumns.DATA, // path index 2
            MediaStore.Video.VideoColumns.DURATION,// duration index 3
            MediaStore.Video.VideoColumns.SIZE,// fileSize index 4
    };

    private static final String[] VIDEO_THUMB_PROJECTION = new String[] {
        MediaStore.Video.Thumbnails.DATA
    };

    @Override
    public boolean dealWith(SocketChannel sc, Action action, Context context) {

        boolean success = false;
        if (action != null) {
            String op = action.getName();
            if (op.equals("GetVideoInfo")) {
                success = getVideoInfo(sc, action, context);
            } else if (op.equals("DeleteVideo")) {
                success = deleteVideo(sc, action, context);
            }
        }
        return success;
    }

    private boolean getVideoInfo(SocketChannel sc, Action action, Context context) {

        StringWriter writer = new StringWriter();
        XmlSerializer serializer = Xml.newSerializer();
        try {
            serializer.setOutput(writer);
            XmlDataDealWith.createPre(action, serializer);
            Cursor videoCursor = context.getContentResolver()
                    .query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, VIDEO_PROJECTION, null,
                            null, null);
            Cursor thumbCursor;
            if (videoCursor != null) {
                while (videoCursor.moveToNext()) {
                    serializer.startTag(null, "item");
                    int videoId = videoCursor.getInt(0);
                    writeSingleTextToXml(serializer, "id", videoId + "");
                    writeSingleTextToXml(serializer, "name", videoCursor.getString(1));
                    writeSingleTextToXml(serializer, "path", videoCursor.getString(2));
                    thumbCursor = context.getContentResolver().query(
                            MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI,
                            VIDEO_THUMB_PROJECTION,
                            MediaStore.Video.Thumbnails.VIDEO_ID + " = " + videoId, null, null);
                    if (thumbCursor != null) {
                        if (thumbCursor.moveToFirst()) {
                            writeSingleTextToXml(serializer, "thumbnailPath",
                                    thumbCursor.getString(0));
                        }
                        thumbCursor.close();
                        thumbCursor = null;
                    }
                    writeSingleTextToXml(serializer, "duration", videoCursor.getString(3));
                    writeSingleTextToXml(serializer, "fileSize", videoCursor.getString(4));
                    serializer.endTag(null, "item");
                }
                videoCursor.close();
            }

            serializer.text("");
            serializer.endTag("", "data");
            serializer.endTag("", "root");
            serializer.endDocument();
            BusinessControl.returnToClient(sc, writer.toString(), context);

        } catch (Exception e) {
            e.printStackTrace();
            BusinessControl.returnToClient(sc,
                    XmlDataDealWith.getSystemErrorString(action.getName(), e.toString()), context);
            return false;
        } finally {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            writer = null;
            serializer = null;
        }

        return true;
    }

    private boolean deleteVideo(SocketChannel sc, Action action, Context context) {
        String source = action.getSource();
        StringReader sr = new StringReader(source);
        XmlPullParser parser = Xml.newPullParser();
        String path = null;
        String id = null;
        boolean success = true;
        try {
            parser.setInput(sr);
            int event = parser.getEventType();
            while (event != XmlPullParser.END_DOCUMENT) {
                switch (event) {
                    case XmlPullParser.START_TAG:
                        if (parser.isEmptyElementTag()) {
                            break;
                        }
                        if ("path".equalsIgnoreCase(parser.getName())) {
                            path = parser.nextText();

                        } else if ("id".equalsIgnoreCase(parser.getName())) {
                            id = parser.nextText();

                        }

                        break;
                    case XmlPullParser.END_TAG:
                        if ("item".equalsIgnoreCase(parser.getName())) {
                            if (TextUtils.isEmpty(path) && TextUtils.isEmpty(id)) {
                                BusinessControl.returnToClient(sc, XmlDataDealWith.getErrorString(
                                        action.getName(), "4",
                                        context.getResources().getString(R.string.paramIsNull_4)),
                                        context);
                                return false;
                            }

                            File file = new File(path);
                            if (!file.delete()) {
                                success = false;
                            }
                            context.getContentResolver().delete(
                                    MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                                    MediaStore.Video.Media._ID + " = " + id, null);
                            context.getContentResolver().delete(
                                    MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI,
                                    MediaStore.Video.Thumbnails.VIDEO_ID + " = " + id, null);
                        }
                        break;

                }
                event = parser.next();
            }
        } catch (Exception e) {
            e.printStackTrace();
            BusinessControl.returnToClient(sc,
                    XmlDataDealWith.getSystemErrorString(action.getName(), e.toString()), context);
            return false;
        }

        BusinessControl.returnToClient(sc, makeReplyCode("DeleteVideo", success), context);
        return success;
    }

    /**
     * 创建一个包含单个值的XML节点，如<TAG>value</TAG>,写入serializer中
     * 
     * @param serializer xml写入器
     * @param tag 节点名
     * @param value 节点值
     * @throws IllegalArgumentException
     * @throws IllegalStateException
     * @throws IOException
     */
    private static void writeSingleTextToXml(XmlSerializer serializer, String tag, String value)
            throws IllegalArgumentException, IllegalStateException, IOException {
        // 值为空时不写入XML
        if (value == null)
            value = "";
        serializer.startTag(null, tag);
        serializer.text(value);
        serializer.endTag(null, tag);
    }

    /**
     * 生成返回xml
     * 
     * @param action
     * @return <?xml version="1.0"
     *         encoding="utf-8"?><root><action>action</action
     *         ><data><result>true或false</result></data></root>
     */
    private static String makeReplyCode(String action, boolean result) {
        return String
                .format("<?xml version='1.0' encoding='utf-8'?><root><action>%s</action><data><result>%s</result></data></root>",
                        action, result);
    }

    // private void printData(Context context, Cursor c) {
    // if (c != null) {
    // StringBuilder sb = new StringBuilder();
    // for (String columnName : c.getColumnNames()) {
    // sb.append(columnName).append(" ");
    // }
    // sb.append("\n");
    // while (c.moveToNext()) {
    // for (String columnName : c.getColumnNames()) {
    // sb.append(c.getString(c.getColumnIndex(columnName))).append(" ");
    // }
    // sb.append("\n");
    // }
    // c.close();
    // Log.i(TAG, sb.toString());
    // }
    // }
}
